<template>
	<s-layout :tabbarshow="false" id="layout" navbar="normal" :autoBack="true" leftIconColor="$uni-text-color" :bgColor="'rgba(0,0,0,0)'" :titleStyle="{  color:'#fff',fontSize:'32rpx' }">
		<map id="map_20221212" class="map" :polygons="polygons" :longitude="position.longitude" :latitude="position.latitude" :markers="covers" :circles="circles">
		
		</map>

		<!-- 列表盒子 -->
		<view class="list_box area">
			<view class="input_search">
				<u-icon class="icon" name="search" color="#5c5c5c" size="24"></u-icon>
				<up-input type="text" class="up-input" placeholder="请输入城市名称"  border="none"  v-model="searchKey"></up-input>
				<view class="button" @tap="searchPosition">搜索</view>
			</view>
			<view class="areas">
				<scroll-view scroll-y class="scroll">
					<view class="list_item" v-for="(item , index) in searchlist" :key="item.id" @tap="changeSelectItem(index)">
						<view class="image">
							<image
								:src="`${baseUrl}/uploads/uniapp_image/staff/Myinterview_icon_location@2.png`"
								mode="scaleToFill"
							/>
						</view>
						<view class="center">
							<view class="title">{{ item.title }}</view>
							<view class="content">{{ item.address }}</view>
						</view>
						<!-- <view class="distance">  {{ item._distance+'m' }} </view> -->
						<view class="item-r">
							<view v-if="item.select" class="picker-checked"></view>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
	</s-layout>

	<!-- 底部提交按钮 -->
    <view>
      <s-button @netWork="submitForm" :text="'确定选点'"></s-button>
    </view>

</template>

<script setup>
	import { ref, reactive, getCurrentInstance, onMounted  } from 'vue';
	import { onLoad } from '@dcloudio/uni-app';
	import { getLocation,isPointInPolygon} from '@/utils/locationUtils';
	import { baseUrl } from "@/sheep/config";
  import QQMapWX from './qqmap-wx-jssdk'
	var qqmapsdk, handleRegionchangeTimmer;
	const props = defineProps({
			polygons: {
				type: Array,
				default: [{
					points: [{
							latitude: '36.829066',
							longitude: '118.025761',
						},
						{
							latitude: '36.825012',
							longitude: '118.066702',
						},
						{
							latitude: '36.81161',
							longitude: '118.042681'
						},
						{
							latitude: '36.801964',
							longitude: '118.034875',
						},
					],
					strokeWidth: 1,
					strokeColor: '#ff000066',
					fillColor: '#ff000016'
				},
				{
					points: [{
							latitude: '36.817369',
							longitude: '118.001311',
						},
						{
							latitude: '36.808682',
							longitude: '118.010281',
						}, {
							latitude: '36.805555',
							longitude: '117.996537',
						},
					],
					strokeWidth: 1,
					strokeColor: '#ff000066',
					fillColor: '#ff000016'
				},
				]
			},
			qqmapsdkKey: {
				type: String,
				default: 'YQNBZ-R4BCH-XDMDZ-WKWDP-FLBNO-FMBHI'
			},
			base_url: {
				type: String,
				default: ''
			},
			sig: {
				type: String,
				default: ''
			}
		})
	const circles = ref([])
	const covers = ref([])
	const { ctx } = getCurrentInstance();
	const canConfirm = ref(false)
	const animateLocation = ref(false) 
	const isChangeSelectItem = ref(true)
	const searchKey = ref('')
	const position = ref({
		latitude: '36.811995',
		longitude: '118.05539'
	})
	const searchlist = ref([])
	
	onLoad((options) => {
		qqmapsdk = new QQMapWX({
			key: 'YQNBZ-R4BCH-XDMDZ-WKWDP-FLBNO-FMBHI',
			BASE_URL: props.base_url
		});
	})
	onMounted(() => {
		// 查看是否传入key值
		if (qqmapsdk.key == '') {
			console.error('需要腾讯地图开发Key，申请地址：https://lbs.qq.com/miniProgram/jsSdk/jsSdkGuide/jsSdkOverview')
			return;
		}
		getLongitudeAndLatitude()
	})
//获取地址
	const getLongitudeAndLatitude = () => {
		getLocation().then((res) => {  
			position.value.latitude = res.latitude
				position.value.longitude = res.longitude
				let obj  = {}
				obj.latitude = position.value.latitude,
				obj.longitude = position.value.longitude,
				obj.id = 1,
				obj.fillColor = '#87cefa50';
				obj.radius = 100;
				obj.strokeWidth = 2;
				obj.color= '#87cefaff';
				obj.width = 20;
				obj.height = 30;
				circles.value.push(obj);
				covers.value.push(obj);
				init()
            }).catch((error) => {  
              sheep.$helper.toast('获取经纬度失败')
                // 如果 Promise 拒绝，则捕获错误  
            });  
	}

	const init = () => {
		animateLocation.value = true;
		handleRegionchangeTimmer = setTimeout(() => {
			renderList();
		}, 400)
	}

	const renderList = () => {
		let mapContext = uni.createMapContext("map_20221212",ctx);
		mapContext.getCenterLocation({
			success: function(rst) {
				let options = {
					location: position.value.latitude + ',' + position.value.longitude,
					get_poi: 1,
					poi_options: 'radius=1000',
					sig: props.sig,
					success: function(res) {
						let isSelect = false;
						// if (res.message == "query ok") {
							searchlist.value = [...res.result.pois];
							
							for (let i = 0; i < searchlist.value.length; i++) {
								searchlist.value.useable = false;
								searchlist.value.select = false;
								for (let j = 0; j < props.polygons.length; j++) {
									if (isPointInPolygon(searchlist.value[i].location.lat, searchlist.value[i].location.lng, props.polygons[j].points)) {
										searchlist[i].value.useable = true;
										if (!isSelect) {
											searchlist[i].value.select = true;
											isSelect = true;
										}
									}
								}

							}
							setTimeout(() => {
								animateLocation.value = false;
							}, 200)
						// }
						if (isSelect) {
							canConfirm.value = true;
						} else {
							canConfirm.value = false;
						}
					},
					fail: function(error) {
						console.log('错误！！',error);
					}
				};
				if (typeof(window) === 'undefined') {
					delete options.sig;
				}
				if (options.sig === '') {
					delete options.sig;
				}
				qqmapsdk.reverseGeocoder(options);
			}
		});
	}


	// 选择
	const changeSelectItem = (index) => {
	
				circles.value = []
				covers.value = []
				if (searchlist.value[index]) {
					for (let i = 0; i < searchlist.value.length; i++) {
						if (i === index) {
							searchlist.value[i].select = true
							isChangeSelectItem.value = true;
							position.value.latitude = searchlist.value[i].location.lat;
							position.value.longitude = searchlist.value[i].location.lng;
							let obj  = {}
							obj.latitude = position.value.latitude,
							obj.longitude = position.value.longitude,
							obj.id = 1,
							obj.fillColor = '#87cefa50';
							obj.radius = 100;
							obj.strokeWidth = 2;
							obj.color= '#87cefaff';
							obj.width = 20;
							obj.height = 30;
							circles.value.push(obj);
							covers.value.push(obj);
						} else {
							searchlist.value[i].select = false;
						}
					}
				}
			}
	// 确认选点
	const gauge_point = ref(true)
	const submitForm = () => {
				searchlist.value.forEach(val => {
					if (val.select) {
						val.polygonIndex = [];
						props.polygons.forEach((polygon, index) => {
							if (isPointInPolygon(val.location.lat, val.location.lng, polygon
									.points)) {
								val.polygonIndex.push(index);
							}
						})
						uni.navigateBack({
							delta:1,
							success:() => {
								uni.$emit('receive',{
									locationAddress:val.address,
									locationLat:val.location.lat,
									locationLon:val.location.lng,
									circles:circles.value,
									covers:covers.value,
									gauge_point:gauge_point.value
								})
							}
						})
					}
				})
	}


	const gaugePoint  = () => {
		uni.getLocation({
			cacheTimeout: 1,
			type: 'gcj02',
			isHighAccuracy: true,
			success: (res) => {
				position.value.latitude = res.latitude
				position.value.longitude = res.longitude
				let obj  = {}
				obj.latitude = position.value.latitude,
				obj.longitude = position.value.longitude,
				obj.id = 1,
				obj.fillColor = '#87cefa50';
				obj.radius = 100;
				obj.strokeWidth = 2;
				obj.color= '#87cefaff';
				obj.width = 20;
				obj.height = 30;
				circles.value.push(obj);
				covers.value.push(obj);
				
			},
			fail: function(error) {
				('获取经纬度失败！',error);
			}
		})
	}
	


	// 用户输入搜索
	const searchPosition =  () => {
		console.log(searchKey.value)
				if (searchKey.value.replace(/\s+/, '') == '') {
					return;
				}
				let searchOptions = {
					keyword: searchKey.value,
					location: {
						latitude: position.value.latitude,
						longitude: position.value.longitude
					},
					sig: props.sig,
					success: function(rst) {
						let isSelect = false;
						// if (rst.message == "query ok") {
							searchlist.value = [...rst.data];
							for (let i = 0; i < searchlist.value.length; i++) {
								searchlist.value.useable = false;
								searchlist.value.select = false;
								for (let j = 0; j < props.polygons.length; j++) {
									if (isPointInPolygon(searchlist.value[i].location.lat,searchlist.value[i].location.lng, props.polygons[j].points)) {
										searchlist.value[i].useable = true;
										if (!isSelect) {
											searchlist.value[i].select = true;
											position.value.latitude = searchlist.value[i].location.lat;
											position.value.longitude = searchlist.value[i].location.lng;
											isSelect = true;
										}
									}
								}

							}
						// }
						if (isSelect) {
							canConfirm.value = true;
						} else {
							canConfirm.value = false;
						}
					}
				};
				if (typeof(window) === 'undefined') {
					delete searchOptions.sig;
				}
				if (searchOptions.sig === '') {
					delete searchOptions.sig;
				}

				qqmapsdk.search(searchOptions);
			}



</script>

<style scoped lang="scss">
	.item-r {
		width: 60rpx;
		display: flex;
		align-items: center;
		align-content: center;
		position: relative;
	}

	.picker-checked {
		background-image: url("data:image/svg+xml,%3Csvg t='1670909673260' class='icon' viewBox='0 0 1024 1024' version='1.1' xmlns='http://www.w3.org/2000/svg' p-id='3763' width='200' height='200'%3E%3Cpath d='M417.185185 768c-9.481481 0-18.962963-3.792593-26.548148-11.377778l-246.518518-246.518518c-15.17037-15.17037-15.17037-37.925926 0-53.096297 15.17037-15.17037 37.925926-15.17037 53.096296 0L417.185185 676.977778l409.6-409.6c15.17037-15.17037 37.925926-15.17037 53.096296 0 15.17037 15.17037 15.17037 37.925926 0 53.096296l-436.148148 436.148148c-7.585185 7.585185-17.066667 11.377778-26.548148 11.377778z' p-id='3764' fill='%231e63ed'%3E%3C/path%3E%3C/svg%3E");
		background-size: cover;
		width: 46rpx;
		height: 46rpx;
		display: block;
		position: absolute;
		right: 30rpx;
		bottom: 0;
	}

	.map {
		width: 100%;
		height: 50vh;
	}
	.area {
		width: calc(100% - 40rpx);
		padding: 22rpx 20rpx;
		border-radius: 20rpx 20rpx 0 0;
	}
	.areas{
		padding: 22rpx 0rpx;
	}
	.list_box {
		// height: 50vh;
		position: absolute;
		bottom:6.5vh;
		background-color: #ffffff;
		border-radius: 20rpx 20rpx 0 0;
		// 输入框 外框
		.input_search {
			height: 58rpx;
			border-radius: 36rpx;
			background-color: #F4F4F4;
			display: flex;
			padding: 7rpx 7rpx;
			.icon {
				display: inline-block;
				width: 100rpx;
				height: 100rpx;
			}
			.up-input {
				margin-left: 50rpx;
			}
			.button {
				width: 150rpx;
				height: 60rpx;
				border-radius: 16px;
				background: linear-gradient(90deg, rgba(0, 56, 247, 1) 0%, rgba(77, 139, 255, 1) 100%);
				text-align: center;
				line-height: 60rpx;
				font-family: PingFangSC;
				color: #FFFFFF;
				font-weight: 500;
				font-size: 30rpx;
				font-style: normal;
				text-decoration: none;
			}
		}

	}
	.scroll {
		height: 34vh;
		.list_item {
			max-height: 186rpx;
			margin-bottom: 18rpx;
			display: flex;
			padding: 20rpx;
			border-bottom: 2rpx solid #f6f6f6;
			// 图片
			.image {
				width: 40rpx;
				image {
					width: 32rpx;
					height: 28rpx;
				}
			}
			// 中心
			.center {
				width: 80%;
				// height: ;
				// 标题
				.title {
					width: 80vw;
					font-family: PingFangSC;
					color: $uni-text-color;
					font-weight: $uni-font-weight;
					font-size: 30rpx;
					font-style: normal;
					text-decoration: none;
					text-align: left;
					margin-bottom: 20rpx;
					white-space: nowrap; /* 不换行 */
					overflow: hidden; /* 超出部分隐藏 */
					text-overflow: ellipsis; /* 超出部分显示省略号 */
				}
				// 内容
				.content {
					width: 100%;
					max-height: 120rpx;
					font-family: PingFangSC;
					color: #999999;
					font-weight: 500;
					font-size: 22rpx;
					font-style: normal;
					text-decoration: none;
					text-align: left;
					overflow: hidden; /* 超出部分隐藏 */
					text-overflow: ellipsis; /* 超出部分显示省略号 */
				}
			}
			// 距离 
			// .distance {
			// 	width: 20%;
			// 	font-family: PingFangSC;
			// 	color: #666666;
			// 	font-weight: 500;
			// 	font-size: $uni-font-size-base;
			// 	font-style: normal;
			// 	text-decoration: none;
			// 	text-align: left;
			// }
		}
	}
	
</style>